﻿# Author: Yunqiao Zhang
# Email: zhangyunqiao@gmail.com

from django.db import models
from django.contrib.auth.models import User
from meet001.commentboard.models import CommentBoard

# Create your models here.
class UserAlreadyActivatedException(Exception):
  def __init__(self):
    Exception.__init__(self, 'User already activated!')

class UserActivationFailedException(Exception):
  def __init__(self):
    Exception.__init__(self, 'User activation failed!')


# A temporary regiter table for users to register and activate.
class Register(models.Model):
  email = models.EmailField(primary_key=True)
  password = models.CharField(max_length=50)
  uuid = models.CharField(max_length=100)
  activated = models.BooleanField()
  name = models.CharField(max_length=20)
  location = models.IntegerField()

  # Activate a user account.
  @staticmethod
  def activate(e, uuid):
    try:
      r = Register.objects.get(pk=e)
      if uuid == r.uuid:
        if r.activated:
          raise UserAlreadyActivatedException()

        # create user.
        user = User.objects.create_user(
            username=e,
            email=e,
            password=r.password)
        profile = Profile.objects.create(
            name=r.name,
            location=r.location,
            user=user)

        # set it as activated.
        r.activated = True
        r.save()
        return r
      else:
        raise UserActivationFailedException()
    except Register.DoesNotExist:
      raise UserActivationFailedException() 

# An additional table for store more information for a user.
class Profile(models.Model):
  name = models.CharField(max_length=20)
  location = models.IntegerField()
  city = models.IntegerField(default=0)
  district = models.IntegerField(default=0)
  photo = models.ImageField(upload_to="photos", default="photos\\default.jpg")
  signature = models.CharField(max_length=100, blank=True)
  GENDER_CHOICES = (
      (u'男', '男'),
      (u'女', '女'),
      )
  sex = models.CharField(max_length=2, choices=GENDER_CHOICES, blank=True)
  profession = models.CharField(max_length=50, blank=True)
  phone = models.CharField(max_length=20, blank=True)
  reason = models.CharField(max_length=512, blank=True)
  user = models.OneToOneField(User)

# Group
class Group(models.Model):
  name = models.CharField(unique=True, max_length=50)
  title = models.CharField(max_length=100)
  label = models.CharField(max_length=100)
  description = models.CharField(max_length=1024)
  location = models.IntegerField()
  city = models.IntegerField(default=0)
  district = models.IntegerField(default=0)
  picture = models.ImageField(upload_to='photos\\group_pic', default='photos\\group_pic\\default.JPG')
  
  #add found date and member_limit
  found_date = models.DateTimeField(auto_now_add=True)
  member_limit = models.IntegerField()
  
  users = models.ManyToManyField(User, through="Membership")
  creator = models.ForeignKey(User, related_name='created_groups')
  comment_board = models.ForeignKey(CommentBoard)

#Meetup
class Meetup(models.Model):
  time_from = models.DateTimeField()
  time_to = models.DateTimeField()
  address = models.CharField(max_length=256)
  group = models.ForeignKey(Group)
  topic = models.CharField(max_length=256)
  description = models.CharField(max_length=2048)
  
  comment_board = models.ForeignKey(CommentBoard)

  def participation(self):
    if hasattr(self, 'cache_participation'):
      return self.cache_participation
    else:
      joinMeetups = JoinMeetup.objects.filter(meetup=self)
      all = self.group.users.count()
      definite = joinMeetups.filter(join_status=0).count()
      refused = joinMeetups.filter(join_status=1).count()
      undecided = all - definite - refused;
      self.cache_participation = {"definite":definite, "refused": refused, "undecided":undecided}
      return self.cache_participation
    

class Membership(models.Model):
  user = models.ForeignKey(User)
  group = models.ForeignKey(Group)
  date_joined = models.DateTimeField(auto_now_add=True)
  # Field for whether this is a admin, or normal member...
  level = models.IntegerField(default=0)

class JoinMeetup(models.Model):
  user = models.ForeignKey(User)
  meetup = models.ForeignKey(Meetup)
  date_joined = models.DateTimeField(auto_now_add = True)
  join_status = models.IntegerField(default=0)
